<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="数据结构,">





  <link rel="alternate" href="/atom.xml" title="xingyys的个人站点" type="application/atom+xml">






<meta name="description" content="引言在了解了数据结构的简单定义之后，则开始进入各种数据结构的学习。数据结构有简单和复杂的区别，现在我们就来学习一种简单的数据结构：线性表。 线性表线性表的定义线性表：零个或多个数据元素的有限序列。它有两个比较关键的点：数据元素是有限的，而且数据元素前后是有联系的。在计算机中，线性表根据它存储结构的不同分成两种类型，分别为：顺序表和链式表。 顺序表顺序表的定义顺序表也就是线性表的顺序存储结构，指的是">
<meta name="keywords" content="数据结构">
<meta property="og:type" content="article">
<meta property="og:title" content="数据结构之线性表">
<meta property="og:url" content="http://blog.xingyys.club/2019/01/28/数据结构之链表/index.html">
<meta property="og:site_name" content="xingyys的个人站点">
<meta property="og:description" content="引言在了解了数据结构的简单定义之后，则开始进入各种数据结构的学习。数据结构有简单和复杂的区别，现在我们就来学习一种简单的数据结构：线性表。 线性表线性表的定义线性表：零个或多个数据元素的有限序列。它有两个比较关键的点：数据元素是有限的，而且数据元素前后是有联系的。在计算机中，线性表根据它存储结构的不同分成两种类型，分别为：顺序表和链式表。 顺序表顺序表的定义顺序表也就是线性表的顺序存储结构，指的是">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://image.xingyys.club/blog/list.png">
<meta property="og:image" content="http://image.xingyys.club/blog/单链表1.png">
<meta property="og:image" content="http://image.xingyys.club/blog/单链表头部插入.png">
<meta property="og:image" content="http://image.xingyys.club/blog/单链表中间插入.png">
<meta property="og:image" content="http://image.xingyys.club/blog/单链表删除结点.png">
<meta property="og:image" content="http://image.xingyys.club/blog/循环链表.png">
<meta property="og:image" content="http://image.xingyys.club/blog/双链表的插入.png">
<meta property="og:image" content="http://image.xingyys.club/blog/双链表的删除.png">
<meta property="og:updated_time" content="2019-02-14T04:56:50.013Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数据结构之线性表">
<meta name="twitter:description" content="引言在了解了数据结构的简单定义之后，则开始进入各种数据结构的学习。数据结构有简单和复杂的区别，现在我们就来学习一种简单的数据结构：线性表。 线性表线性表的定义线性表：零个或多个数据元素的有限序列。它有两个比较关键的点：数据元素是有限的，而且数据元素前后是有联系的。在计算机中，线性表根据它存储结构的不同分成两种类型，分别为：顺序表和链式表。 顺序表顺序表的定义顺序表也就是线性表的顺序存储结构，指的是">
<meta name="twitter:image" content="http://image.xingyys.club/blog/list.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xingyys.club/2019/01/28/数据结构之链表/">





  <title>数据结构之线性表 | xingyys的个人站点</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xingyys的个人站点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学习和分享</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-users"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xingyys.club/2019/01/28/数据结构之链表/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xingyys">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xingyys的个人站点">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">数据结构之线性表</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-28T12:00:17+08:00">
                2019-01-28
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/随笔/" itemprop="url" rel="index">
                    <span itemprop="name">随笔</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>在了解了数据结构的简单定义之后，则开始进入各种数据结构的学习。数据结构有简单和复杂的区别，现在我们就来学习一种简单的数据结构：<code>线性表</code>。</p>
<h1 id="线性表"><a href="#线性表" class="headerlink" title="线性表"></a>线性表</h1><h2 id="线性表的定义"><a href="#线性表的定义" class="headerlink" title="线性表的定义"></a>线性表的定义</h2><p><code>线性表：零个或多个数据元素的有限序列。</code><br>它有两个比较关键的点：数据元素是有限的，而且数据元素前后是有联系的。<br>在计算机中，线性表根据它存储结构的不同分成两种类型，分别为：<code>顺序表</code>和<code>链式表</code>。</p>
<h2 id="顺序表"><a href="#顺序表" class="headerlink" title="顺序表"></a>顺序表</h2><h3 id="顺序表的定义"><a href="#顺序表的定义" class="headerlink" title="顺序表的定义"></a>顺序表的定义</h3><p><code>顺序表也就是线性表的顺序存储结构，指的是用一段地址连续单元依次存储线性表的数据元素。</code></p>
<p><img src="http://image.xingyys.club/blog/list.png" alt=""></p>
<h3 id="顺序表的实现"><a href="#顺序表的实现" class="headerlink" title="顺序表的实现"></a>顺序表的实现</h3><p>顺序表在计算机中应用非常广泛，同时各种编程语言也都有它的实现。在Python中就有一个<code>list</code>数据结构。让我们来看看怎么表现：<br><strong>定义顺序表</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">List</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, max)</span>:</span></span><br><span class="line">        self._max = max</span><br><span class="line">        self._num = <span class="number">0</span></span><br><span class="line">        self._data = []</span><br></pre></td></tr></table></figure></p>
<p><strong>添加元素</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">append</span><span class="params">(self, data)</span>:</span> <span class="comment"># 尾端插入</span></span><br><span class="line">    <span class="keyword">if</span> self._num + <span class="number">1</span> &gt;= self._max:  <span class="comment"># 表已满</span></span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"out of range"</span>)</span><br><span class="line">    self._num += <span class="number">1</span></span><br><span class="line">    self._data.append(data)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">insert</span><span class="params">(self, index, data)</span>:</span> <span class="comment"># 指定位置插入</span></span><br><span class="line">    <span class="keyword">if</span> self._num + <span class="number">1</span> &gt;= self._max:  <span class="comment"># 表已满</span></span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"out of range"</span>)</span><br><span class="line">    <span class="keyword">if</span> index &gt; self._num <span class="keyword">or</span> index &lt;  <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"invalid index"</span>)</span><br><span class="line">    self._data.append(<span class="number">0</span>)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(index, self._num):</span><br><span class="line">        self._data[self._num-i+index] = self._data[self._num-i+index<span class="number">-1</span>]</span><br><span class="line">    self._num += <span class="number">1</span></span><br><span class="line">    self._data[index] = data</span><br></pre></td></tr></table></figure></p>
<p>顺序表的查找是从首个元素的地址在加上对应个数，时间为常亮量；但当插入和删除时，尾部需要循环， 所以插入时间复杂度为：<code>O(n)</code>，尾端插入为<code>O(1)</code></p>
<p><strong>删除元素</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pop</span><span class="params">(self)</span>:</span> <span class="comment"># 尾端删除</span></span><br><span class="line">    <span class="keyword">if</span> self._num == <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"empty list"</span>)</span><br><span class="line">    v = self._data.pop()</span><br><span class="line">    self._num -= <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> v</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">delete</span><span class="params">(self, index)</span>:</span> <span class="comment"># 指定位置删除</span></span><br><span class="line">    <span class="keyword">if</span> self._num == <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"empty list"</span>)</span><br><span class="line">    <span class="keyword">if</span> index &lt; <span class="number">0</span> <span class="keyword">or</span> index &gt; self._num:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"invalid index"</span>)</span><br><span class="line">    v = self._data[index]</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(index, self._num):</span><br><span class="line">        self._data[i<span class="number">-1</span>] = self._data[i]</span><br><span class="line">    self._num -= <span class="number">1</span></span><br><span class="line">    self._data = self._data[<span class="number">0</span>:self._num]</span><br><span class="line">    <span class="keyword">return</span> v</span><br></pre></td></tr></table></figure></p>
<p>删除时间复杂度为：<code>O(n)</code>，尾端删除为<code>O(1)</code></p>
<p><strong>查找元素和修改</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(self, i)</span>:</span> <span class="comment"># 查找对应位置元素</span></span><br><span class="line">    <span class="keyword">if</span> i &lt; <span class="number">0</span> <span class="keyword">or</span> i &gt; self._num:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"invalid index"</span>)</span><br><span class="line">    <span class="keyword">return</span> self._data[i]</span><br><span class="line">        </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update</span><span class="params">(self, index, data)</span>:</span> <span class="comment"># 更新对应位置元素</span></span><br><span class="line">    <span class="keyword">if</span> index &lt; <span class="number">0</span> <span class="keyword">or</span> index &gt; self._num:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"invalid index"</span>)</span><br><span class="line">    self._data[index] = data</span><br></pre></td></tr></table></figure></p>
<p>查看和修改的都为：<code>O(1)</code></p>
<h3 id="顺序表的优缺点"><a href="#顺序表的优缺点" class="headerlink" title="顺序表的优缺点"></a>顺序表的优缺点</h3><p><strong>优点：</strong></p>
<ul>
<li>查找快</li>
<li>结构简单</li>
<li>管理方便</li>
</ul>
<p><strong>缺点</strong></p>
<ul>
<li>插入和删除操作需要移动大量元素</li>
<li>当线性表长度变化较大时，难以确定存储空间的容量</li>
<li>容易在内部形成大量的无用元素，浪费空间</li>
<li>数据元素多时，不容易在内存划出大量连续空间</li>
</ul>
<h2 id="链式表"><a href="#链式表" class="headerlink" title="链式表"></a>链式表</h2><h3 id="链式表的定义"><a href="#链式表的定义" class="headerlink" title="链式表的定义"></a>链式表的定义</h3><p><code>链式表也称为线性表的链式存储方式</code>。<br>链式表中每个元素独立，它们存储的位置可能连续也也可能不连续，但每个结点都有一个空间存储下一个元素的位置。<br>链式表根据每个结点的不同，也有<code>单链表</code>，<code>双链表</code>，<code>循环链表</code>等区别。</p>
<h3 id="单链表"><a href="#单链表" class="headerlink" title="单链表"></a>单链表</h3><p><code>单链表就是链表的每个结点有两个空间，分别保存这结点的值和下一个结点的内存地址。</code></p>
<p><img src="http://image.xingyys.club/blog/单链表1.png" alt=""></p>
<p><strong>单链表的结点实现</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span>:</span></span><br><span class="line">    <span class="string">"""单链表的节点</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, elem, next=None)</span>:</span></span><br><span class="line">        <span class="string">"""初始化一个新节点</span></span><br><span class="line"><span class="string">        :elem object 节点的元素值</span></span><br><span class="line"><span class="string">        :next object 下一个节点的位置</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        self.elem = elem</span><br><span class="line">        self.next = next</span><br></pre></td></tr></table></figure></p>
<p>使用<code>Python</code>的对象很简单的实现单链表的结点。</p>
<p><strong>单链表的实现</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SingleLinkList</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self._length = <span class="number">0</span></span><br><span class="line">        self.head = <span class="keyword">None</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">is_empty</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self._length == <span class="number">0</span> <span class="keyword">and</span> self.head <span class="keyword">is</span> <span class="keyword">None</span></span><br></pre></td></tr></table></figure></p>
<p><strong>单链表的读取</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(self, value)</span>:</span></span><br><span class="line">    <span class="string">"""输出元素在表中的位置"""</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">raise</span> ValueError(<span class="string">"&#123;&#125; is not in single list"</span>.format(value))</span><br><span class="line">    n = <span class="number">0</span></span><br><span class="line">    <span class="keyword">if</span> self.head.elem == value:</span><br><span class="line">        <span class="keyword">return</span> n</span><br><span class="line">    p = self.head</span><br><span class="line">    <span class="keyword">while</span> p.next <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">        n += <span class="number">1</span></span><br><span class="line">        p = p.next</span><br><span class="line">        <span class="keyword">if</span> p.elem == value:</span><br><span class="line">            <span class="keyword">return</span> n</span><br><span class="line">    <span class="keyword">raise</span> ValueError(<span class="string">"&#123;&#125; is not in single list"</span>.format(value))</span><br></pre></td></tr></table></figure></p>
<p>读取最坏的情况是循环整张表，所以为<code>O(n)</code></p>
<p><strong>单链表的插入</strong><br>单链表插入有两种情况，一种是头部插入，如图：</p>
<p><img src="http://image.xingyys.club/blog/单链表头部插入.png" alt=""><br>有三个步骤：</p>
<ul>
<li>创建一个结点并存入数据。</li>
<li>把原链表首结点的链接存入新结点的链接域next。</li>
<li>修改表头变量，使之指向新结点。<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">prepend</span><span class="params">(self, value)</span>:</span></span><br><span class="line">    <span class="string">"""头部添加元素"""</span></span><br><span class="line">    self._length += <span class="number">1</span></span><br><span class="line">    self.head = Node(value, self.head)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>首部插入时间复杂度为<code>O(1)</code></p>
<p>还有一种是一般插入：<br><img src="http://image.xingyys.club/blog/单链表中间插入.png" alt=""><br>同样的有三个步骤：</p>
<ul>
<li>创建一个新结点并存入数据。</li>
<li>新结点的next指向到上一个结点的next。</li>
<li>把上一个结点的next指向到新结点。<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">append</span><span class="params">(self, value)</span>:</span></span><br><span class="line">    <span class="string">"""尾部添加元素"""</span></span><br><span class="line">    self._length += <span class="number">1</span></span><br><span class="line">    <span class="comment"># 第一种情况，如果链表为空，直接添加头部</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        self.head = Node(value)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="comment"># 第二种情况，需要循环取得尾部元素，再添加</span></span><br><span class="line">    p = self.head</span><br><span class="line">    <span class="keyword">while</span> p.next <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">        p = p.next</span><br><span class="line">    p.next = Node(value)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">insert</span><span class="params">(self, index, value)</span>:</span></span><br><span class="line">    <span class="string">"""在指定位置插入元素"""</span></span><br><span class="line">    <span class="keyword">if</span> index &lt; <span class="number">0</span> <span class="keyword">or</span> index &gt; self._length<span class="number">-1</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"single list out of range"</span>)</span><br><span class="line">    self._length += <span class="number">1</span></span><br><span class="line">    <span class="keyword">if</span> index == <span class="number">0</span> <span class="keyword">and</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        self.head = Node(value)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    p = self.head</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(index):</span><br><span class="line">        p = p.next</span><br><span class="line">    p.next = Node(value, p.next)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>因为插入之后步不要重新整理数据，指定位置和尾部插入的时间复杂度为<code>O(n)</code>。</p>
<p><strong>单链表删除</strong><br>单链表的头部删除和其他位置删除也是不同的。<br>头部删除只需要将head指向到原头部元素的下一个元素，在清除原head就可以了（有GC的语言不需要，而像C语言就需要开发者手动清除）。<br>一般情况的删除有三个步骤：</p>
<ul>
<li>找到删除结点的上一个结点，设为pre</li>
<li>将pre的next指向到删除结点的next</li>
<li>删除指定结点</li>
</ul>
<p><img src="http://image.xingyys.club/blog/单链表删除结点.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">shift</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="string">"""删除头部"""</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"single list is empty"</span>)</span><br><span class="line">    self._length -= <span class="number">1</span></span><br><span class="line">    e = self.head.elem</span><br><span class="line">    self.head = self.head.next</span><br><span class="line">    <span class="keyword">return</span> e</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pop</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="string">"""尾部删除元素"""</span></span><br><span class="line">    <span class="comment"># 空表报错</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"single list is empty"</span>)</span><br><span class="line">    self._length -= <span class="number">1</span></span><br><span class="line">    p = self.head</span><br><span class="line">    <span class="comment"># 链表中只有一个元素</span></span><br><span class="line">    <span class="keyword">if</span> p.next <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        e = p.elem</span><br><span class="line">        self.head = <span class="keyword">None</span></span><br><span class="line">        <span class="keyword">return</span> e</span><br><span class="line">    <span class="keyword">while</span> p.next.next <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">        p = p.next</span><br><span class="line">    e = p.elem</span><br><span class="line">    p.next = <span class="keyword">None</span></span><br><span class="line">    <span class="keyword">return</span> e</span><br><span class="line">		</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">remove</span><span class="params">(self, index)</span>:</span></span><br><span class="line">    <span class="string">"""删除指定位置的元素"""</span></span><br><span class="line">    <span class="keyword">if</span> index &lt; <span class="number">0</span> <span class="keyword">or</span> index &gt; self._length<span class="number">-1</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"single list out of range"</span>)</span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"single list is empty"</span>)</span><br><span class="line">    self._length -= <span class="number">1</span></span><br><span class="line">    p = self.head</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(index<span class="number">-1</span>):</span><br><span class="line">        p = p.next</span><br><span class="line">    e = p.next.elem</span><br><span class="line">    p.next = p.next.next</span><br><span class="line">    <span class="keyword">return</span> e</span><br></pre></td></tr></table></figure>
<p>头部删除为<code>O(1)</code>，尾部和其他位置均为<code>O(n)</code>。</p>
<h3 id="链式表的优缺点"><a href="#链式表的优缺点" class="headerlink" title="链式表的优缺点"></a>链式表的优缺点</h3><p>优点：</p>
<ul>
<li>解决顺序表空间申请不方便和空间浪费问题。</li>
<li>一般的插入和删除性能是优于顺序表的，因为结点找到后直接操作，不需要再做处理。</li>
</ul>
<p>缺点：</p>
<ul>
<li>占用的空间更大，因为有一个next域。</li>
<li>查看的性能为<code>O(n)</code>，劣于顺序表。</li>
<li>更难操作和理解。</li>
</ul>
<h3 id="循环链表"><a href="#循环链表" class="headerlink" title="循环链表"></a>循环链表</h3><p>单链表的一种变形为循环单链表。实现方式就是链表中的尾部结点的next指向到首部结点，形成一个循环，同时链表记录尾结点，使尾部插入删除都变为<code>O(1)</code>。</p>
<p><img src="http://image.xingyys.club/blog/循环链表.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CycleLinkList</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.rear = <span class="keyword">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">is_empty</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.rear <span class="keyword">is</span> <span class="keyword">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">prepend</span><span class="params">(self, value)</span>:</span></span><br><span class="line">        <span class="string">"""前端插入"""</span></span><br><span class="line">        p = Node(value)</span><br><span class="line">        <span class="keyword">if</span> self.rear <span class="keyword">is</span> <span class="keyword">None</span>: </span><br><span class="line">            p.next = p <span class="comment"># 建立一个节点的环</span></span><br><span class="line">            self.rear = p</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            p.next = self.rear.next</span><br><span class="line">            self.rear.next = p</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">append</span><span class="params">(self, value)</span>:</span></span><br><span class="line">        <span class="string">"""尾端插入"""</span></span><br><span class="line">        self.lpush(value)</span><br><span class="line">        self.rear = self.rear.next</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">pop</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""后端弹出"""</span></span><br><span class="line">        <span class="keyword">if</span> self.rear <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">            <span class="keyword">raise</span> IndexError(<span class="string">"in pop of CycleList"</span>)</span><br><span class="line">        p = self.rear.next</span><br><span class="line">        <span class="keyword">if</span> self.rear <span class="keyword">is</span> p: <span class="comment"># 链表只有一个节点的情况</span></span><br><span class="line">            self.rear = <span class="keyword">None</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">while</span> p.next <span class="keyword">is</span> <span class="keyword">not</span> self.rear:</span><br><span class="line">                p = p.next</span><br><span class="line">            p.next = self.rear.next</span><br><span class="line">            self.rear = p</span><br><span class="line">        <span class="keyword">return</span> p.elem</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">shift</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""前端弹出"""</span></span><br><span class="line">        <span class="keyword">if</span> self.rear <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">            <span class="keyword">raise</span> IndexError(<span class="string">"in lpop of CycleList"</span>)</span><br><span class="line">        p = self.rear.next</span><br><span class="line">        <span class="keyword">if</span> self.rear <span class="keyword">is</span> p:</span><br><span class="line">            self.rear = <span class="keyword">None</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.rear.next = p.next</span><br><span class="line">        <span class="keyword">return</span> p.elem</span><br></pre></td></tr></table></figure>
<h3 id="双链表"><a href="#双链表" class="headerlink" title="双链表"></a>双链表</h3><p>单链表只有一个方向的链接，只能做一个方向的循环。加入我们需要查看当前元素的上一个元素，就只能重新循环了。为了两边都能高效的循环，就引入了<code>双链表</code>。它的每个结点有三个存储域：<code>data</code>、<code>prev</code>和<code>next</code>。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DNode</span>:</span></span><br><span class="line">    <span class="string">"""双链表的节点，包含元素，下一个节点的链接，上一个节点的链接"""</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, elem, prev=None, next_=None)</span>:</span></span><br><span class="line">        self.elem = elem</span><br><span class="line">        self.prev = prev</span><br><span class="line">        self.next = next_</span><br></pre></td></tr></table></figure></p>
<p>而双链表的插入和删除在原来的基础上，还需要修改<code>prev</code>域的值。</p>
<p><strong>双链表的插入</strong></p>
<ul>
<li>创建一个新的结点</li>
<li>新结点的next指向上一个结点的next</li>
<li>新结点的prev指向下一个结点的prev</li>
<li>上一个结点的next指向新结点</li>
<li>下一个结点的prev指向新结点</li>
</ul>
<p><img src="http://image.xingyys.club/blog/双链表的插入.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">prepend</span><span class="params">(self, value)</span>:</span></span><br><span class="line">    <span class="string">"""前端插入"""</span></span><br><span class="line">    self.length += <span class="number">1</span></span><br><span class="line">    p = DNode(value, self.rear, self.head)</span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        self.rear = p</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        p.next.prev = p</span><br><span class="line">    self.head = p</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">append</span><span class="params">(self, value)</span>:</span></span><br><span class="line">    <span class="string">"""后端插入"""</span></span><br><span class="line">    self.length += <span class="number">1</span></span><br><span class="line">    p = DNode(value, self.rear, <span class="keyword">None</span>)</span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>: <span class="comment"># 空表</span></span><br><span class="line">        self.head = p</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        p.prev.next = p</span><br><span class="line">    self.rear = p</span><br><span class="line">    </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">insert</span><span class="params">(self, index, data)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> index &lt; <span class="number">0</span> <span class="keyword">or</span> index &gt; self.length:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"out of range"</span>)</span><br><span class="line">    p = self.head</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(index):</span><br><span class="line">        p = p.next</span><br><span class="line">    node = DNode(data, p.next.prev, p.prev.next)</span><br><span class="line">    p.next.prev = node</span><br><span class="line">    p.prev.next = node</span><br><span class="line">    self.length += <span class="number">1</span></span><br></pre></td></tr></table></figure>
<p><strong>双链表的删除</strong></p>
<ul>
<li>将删除结点的上一个结点的next指向到删除结点的下一个结点</li>
<li>将删除结点的下一个结点的prev指向到删除结点的上衣结点</li>
<li>删除对应结点</li>
</ul>
<p><img src="http://image.xingyys.club/blog/双链表的删除.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pop</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="string">"""后端删除"""</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"in pop of DoubleLinkList"</span>)</span><br><span class="line">    e = self.rear.elem</span><br><span class="line">    self.rear = self.rear.prev</span><br><span class="line">    <span class="keyword">if</span> self.rear <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        self.head = <span class="keyword">None</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        self.rear.next = <span class="keyword">None</span></span><br><span class="line">    <span class="keyword">return</span> e</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">shift</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="string">"""前端删除"""</span></span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"in shift of DoubleLinkList"</span>)</span><br><span class="line">    e = self.head.elem</span><br><span class="line">    self.head = self.head.next</span><br><span class="line">    <span class="keyword">if</span> self.head <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        self.rear = <span class="keyword">None</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        self.head.prev = <span class="keyword">None</span></span><br><span class="line">    <span class="keyword">return</span> e</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">delete</span><span class="params">(self, index)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> index &lt; <span class="number">0</span> <span class="keyword">or</span> index &gt; self.length:</span><br><span class="line">        <span class="keyword">raise</span> IndexError(<span class="string">"out of range"</span>)</span><br><span class="line">    <span class="keyword">if</span> index == <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">return</span> self.shift()</span><br><span class="line">    <span class="keyword">if</span> index == self.length:</span><br><span class="line">        <span class="keyword">return</span> self.pop()</span><br><span class="line">    p = self.head</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(index):</span><br><span class="line">        p = p.next</span><br><span class="line">    v = p.elem</span><br><span class="line">    p.prev.next = p.next</span><br><span class="line">    p.next.prev = p.prev</span><br><span class="line">    <span class="keyword">return</span> v</span><br></pre></td></tr></table></figure>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>在生产和应用中，线性表这种基本的数据结构应用场景非常多，而一些复杂的数据结构也是在这些基础上实现。这里总的学习了线性表中的顺序存储和链式存储。而链式表中还有一个常用的变形，如<code>循环链表</code>，<code>双链表</code>等。这些理解起来必单链表难，但带来性能上的增长也是明显的。这也是算法中一种常用的方法。</p>
<h1 id="参考书籍"><a href="#参考书籍" class="headerlink" title="参考书籍"></a>参考书籍</h1><ul>
<li>大话数据结构</li>
<li>数据结构与算法Python实现</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="xingyys 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/数据结构/" rel="tag"># 数据结构</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/26/linux上使用udev创建裸设备/" rel="next" title="linux上使用udev创建裸设备">
                <i class="fa fa-chevron-left"></i> linux上使用udev创建裸设备
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/30/数据结构之栈与队列/" rel="prev" title="数据结构之栈与队列">
                数据结构之栈与队列 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MjIyNC8xODc3MQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpeg" alt="xingyys">
            
              <p class="site-author-name" itemprop="name">xingyys</p>
              <p class="site-description motion-element" itemprop="description">你的话是我脚前的灯，是我路上的光。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xingyys" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#引言"><span class="nav-number">1.</span> <span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#线性表"><span class="nav-number">2.</span> <span class="nav-text">线性表</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#线性表的定义"><span class="nav-number">2.1.</span> <span class="nav-text">线性表的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#顺序表"><span class="nav-number">2.2.</span> <span class="nav-text">顺序表</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#顺序表的定义"><span class="nav-number">2.2.1.</span> <span class="nav-text">顺序表的定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#顺序表的实现"><span class="nav-number">2.2.2.</span> <span class="nav-text">顺序表的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#顺序表的优缺点"><span class="nav-number">2.2.3.</span> <span class="nav-text">顺序表的优缺点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#链式表"><span class="nav-number">2.3.</span> <span class="nav-text">链式表</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#链式表的定义"><span class="nav-number">2.3.1.</span> <span class="nav-text">链式表的定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#单链表"><span class="nav-number">2.3.2.</span> <span class="nav-text">单链表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#链式表的优缺点"><span class="nav-number">2.3.3.</span> <span class="nav-text">链式表的优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#循环链表"><span class="nav-number">2.3.4.</span> <span class="nav-text">循环链表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#双链表"><span class="nav-number">2.3.5.</span> <span class="nav-text">双链表</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考书籍"><span class="nav-number">4.</span> <span class="nav-text">参考书籍</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xingyys</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
